package com.employeemanage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.employeemanage.domain.bean.TblProduct;
import com.employeemanage.domain.bean.TblPurchase;
import com.employeemanage.domain.bean.TblSupplier;
import com.employeemanage.domain.resp.PageResult;
import com.employeemanage.domain.vo.PurchaseAddResponseVo;
import com.employeemanage.domain.vo.PurchaseAddVo;
import com.employeemanage.domain.vo.PurchaseListVo;
import com.employeemanage.domain.vo.PurchaseResponseVo;
import com.employeemanage.mapper.TblPurchaseMapper;
import com.employeemanage.service.TblProductService;
import com.employeemanage.service.TblPurchaseService;
import com.employeemanage.service.TblSupplierService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
* @author 郭可欣
* @description 针对表【tbl_purchase(采购记录)】的数据库操作Service实现
* @createDate 2025-07-05 14:20:29
*/
@Service
public class TblPurchaseServiceImpl extends ServiceImpl<TblPurchaseMapper, TblPurchase>
    implements TblPurchaseService{

    @Autowired
    private TblSupplierService supplierService;
    
    @Autowired
    private TblProductService productService;

    @Override
    public PageResult<TblPurchase> getPurchaseList(PurchaseListVo purchaseListVo) {
        Page<TblPurchase> page = new Page<>(
            purchaseListVo.getPageNum() != null ? purchaseListVo.getPageNum() : 1,
            purchaseListVo.getPageSize() != null ? purchaseListVo.getPageSize() : 10
        );

        LambdaQueryWrapper<TblPurchase> queryWrapper = new LambdaQueryWrapper<>();
        // 这里只能查purchase表字段，supplierName/productName如需联表查可用VO扩展
        if (purchaseListVo.getStartDate() != null && !purchaseListVo.getStartDate().isEmpty()) {
            queryWrapper.ge(TblPurchase::getPurchaseDate, purchaseListVo.getStartDate());
        }
        if (purchaseListVo.getEndDate() != null && !purchaseListVo.getEndDate().isEmpty()) {
            queryWrapper.le(TblPurchase::getPurchaseDate, purchaseListVo.getEndDate());
        }
        if (purchaseListVo.getSupplierName() != null && !purchaseListVo.getSupplierName().isEmpty()) {
            // 这里只能查supplierId，如需查supplierName需自定义SQL或VO扩展
        }
        if (purchaseListVo.getProductName() != null && !purchaseListVo.getProductName().isEmpty()) {
            // 这里只能查productId，如需查productName需自定义SQL或VO扩展
        }
        queryWrapper.orderByDesc(TblPurchase::getPurchaseDate);

        Page<TblPurchase> resultPage = this.page(page, queryWrapper);
        return new PageResult<>(resultPage);
    }

    @Override
    @Transactional
    public PurchaseAddResponseVo addPurchase(PurchaseAddVo purchaseAddVo) {
        // 验证供应商是否存在
        TblSupplier supplier = supplierService.getById(purchaseAddVo.getSupplierId());
        if (supplier == null) {
            throw new RuntimeException("供应商不存在");
        }
        
        // 验证商品是否存在
        TblProduct product = productService.getById(purchaseAddVo.getProductId());
        if (product == null) {
            throw new RuntimeException("商品不存在");
        }
        
        // 计算总金额
        BigDecimal totalAmount = purchaseAddVo.getUnitPrice().multiply(new BigDecimal(purchaseAddVo.getQuantity()));
        
        // 创建进货记录
        TblPurchase purchase = new TblPurchase();
        purchase.setSupplierId(purchaseAddVo.getSupplierId());
        purchase.setProductId(purchaseAddVo.getProductId());
        purchase.setQuantity(purchaseAddVo.getQuantity());
        purchase.setUnitPrice(purchaseAddVo.getUnitPrice());
        purchase.setTotalAmount(totalAmount);
        purchase.setCreatedAt(new Date());
        
        // 解析进货日期
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date purchaseDate = sdf.parse(purchaseAddVo.getPurchaseDate());
            purchase.setPurchaseDate(purchaseDate);
        } catch (ParseException e) {
            throw new RuntimeException("进货日期格式错误，请使用yyyy-MM-dd格式");
        }
        
        // 保存进货记录
        save(purchase);
        
        // 更新商品库存
        product.setStock(product.getStock() + purchaseAddVo.getQuantity());
        productService.updateById(product);
        
        // 构建响应结果
        PurchaseAddResponseVo response = new PurchaseAddResponseVo();
        response.setId(purchase.getId());
        response.setTotalAmount(totalAmount);
        
        return response;
    }
}




